package com.company.tree;

import com.company.TreeNode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * @author jrue
 * @version 1.0
 * @date 2020/1/27 14:12
 */
public class BinaryTreeLevelOrderTraversalii {
    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        List<List<Integer>> lists = new ArrayList<>();
        if (root == null) return lists;

        Queue<TreeNode> queue = new LinkedList<>();

        int preNodeCount = 1;
        int thisNodeCount = 0;

        queue.offer(root);
        List<Integer> data = new ArrayList<>();
        while (!queue.isEmpty()) {
            TreeNode thisNode = queue.poll();
            data.add(thisNode.val);
            preNodeCount--;

            if (thisNode.left != null) {
                thisNodeCount++;
                queue.offer(thisNode.left);
            }
            if (thisNode.right != null) {
                thisNodeCount++;
                queue.offer(thisNode.right);
            }

            if (preNodeCount == 0) {
                preNodeCount = thisNodeCount;
                thisNodeCount=0;
                lists.add(0,data);
                data = new ArrayList<>();
            }
        }
        return lists;
    }
}
